﻿#region License
/* ---------------------------------------------------------------- *
 *
 * This file is part of the Xcoordination Application Space
 * ("XcoAppSpace") http://www.xcoordination.com
 *
 * Copyright (C) 2009 Xcoordination http://www.xcoordination.com
 *
 * XcoAppSpace is free software; you can redistribute it and/or
 * modify it under the terms of version 2 of the GNU General
 * Public License as published by the Free Software Foundation.
 *
 * XcoAppSpace is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses/
 * or write to the Free Software Foundation, Inc., 51 Franklin
 * Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * ---------------------------------------------------------------- */
#endregion

using System;
using System.Threading;
using Microsoft.Ccr.Core;

namespace XcoAppSpaces.Dialogs
{
    public interface IDialogMessageHandler
    {
        void Execute(object message);
        bool Match(DialogMessage message);
    }


    public class DialogMessageHandler<TMessage> : IDialogMessageHandler
    {
        protected SynchronizationContext syncContext;
        protected Handler<TMessage> handler;
        protected Func<TMessage, bool> condition;


        public DialogMessageHandler(){}

        public DialogMessageHandler(Handler<TMessage> handler, SynchronizationContext syncContext) : this(handler, syncContext, m => true) {}
        public DialogMessageHandler(Handler<TMessage> handler, SynchronizationContext syncContext, Func<TMessage, bool> condition)
        {
            this.handler = handler;
            this.syncContext = syncContext;
            this.condition = condition;
        }

        public void Execute(object message)
        {
            if (this.syncContext == null)
                this.handler((TMessage)message);
            else
            {
                //TODO: copy causalities into sync context
                this.syncContext.Send(delegate { this.handler((TMessage)message); }, null);
            }
        }

        public bool Match(DialogMessage message)
        {
            // check message type first so that only messages of matching type
            // are passed to the condition.
            return typeof(TMessage) == message.Payload.GetType() &&
                   condition((TMessage)message.Payload);
        }
    }
}
